import React, { useContext } from 'react';
import { Table, Tag } from 'antd';
import { groupBy } from 'lodash';
import classnames from 'classnames';

import { numberFormat } from '@/utils/formatterUtil';

import { housePlaceEnum, socialTypeEnum, insuranceBaseTypeEnum, decimalTypeEnum } from '@/pages/SalaryManage/enum';
import {
    amountColumn,
    percentColumn
} from '@/pages/SalaryManage/utils/TableUtil';
import EmptyPlaceHolder from '@/pages/SalaryManage/components/EmptyPlaceHolder';
import BaseSettingContext from './BaseSettingContext';
import style from './index.less';

const MODIFY_STATUS = {
    // 正常
    0: {
        tag: null,
        rowTheme: null
    },
    // 新增
    1: {
        tag: {
            text: '新增',
            color: 'cyan'
        },
        rowTheme: 'add'
    },
    // 删除
    2: {
        tag: {
            text: '删除',
            color: 'red'
        },
        rowTheme: 'delete'
    },
    // 编辑
    3: {
        tag: {
            text: '编辑',
            color: 'blue'
        },
        rowTheme: null
    }
};

const onFieldCell = field => record =>
    (record?.[field] === 1 ? { 'data-cell-theme': 'modified' } : { 'data-cell-theme': '' });

/**
 * 表格列定义
 * @returns []
 */
const tableColumn = (showCompareEffect, decimalPlaces) => [
    {
        title: '户口归属',
        dataIndex: 'housePlace',
        width: 100,
        render: (text, record) => ({
            children: housePlaceEnum.getShowName(text),
            props: {
                rowSpan: record.v_rowSpan
            }
        }),
        ellipsis: true
    },
    {
        title: '险金',
        dataIndex: 'socialType',
        width: 150,
        render: (text, record) => {
            const statusMapperInfo = MODIFY_STATUS[record.status] ?? MODIFY_STATUS[0];
            const tagInfo = showCompareEffect ? statusMapperInfo.tag : MODIFY_STATUS['0'];

            return (
                <div>
                    <span className={style.mr8}>
                        {record.status != null
                            ? socialTypeEnum.getShowName(text)
                            : <EmptyPlaceHolder />}</span>
                    {tagInfo ? <Tag color={tagInfo.color}>{tagInfo.text}</Tag> : null}
                </div>
            );
        },
        ellipsis: true
    },
    {
        title: '基数取值',
        dataIndex: 'baseType',
        width: 150,
        render: text => (
            <span >
                {text
                    ? insuranceBaseTypeEnum.getShowName(text)
                    : <EmptyPlaceHolder />}</span>
        ),
        ellipsis: true
    },
    amountColumn({
        title: '最低缴交基数',
        dataIndex: 'minPayAmt',
        onCell: onFieldCell('isMinPayAmt'),
        ellipsis: true
    }, { decimalPlaces }),
    amountColumn({
        title: '缴交基数',
        dataIndex: 'basePayAmt',
        onCell: onFieldCell('isBasePayAmt'),
        ellipsis: true
    }, { decimalPlaces }),

    {
        title: '单位',
        dataIndex: '',
        children: [
            percentColumn({
                title: '比例',
                dataIndex: 'companyRate',
                onCell: onFieldCell('isCompanyRate')
            }, { decimalPlaces }),
            amountColumn({
                title: '金额',
                dataIndex: 'companyAmt',
                onCell: onFieldCell('isCompanyAmt')
            }, { decimalPlaces })
        ],
        ellipsis: true
    },
    {
        title: '个人',
        dataIndex: '比例',
        children: [
            percentColumn({
                title: '比例',
                dataIndex: 'personRate',
                onCell: onFieldCell('isPersonRate'),
                ellipsis: true
            }, { decimalPlaces }),
            amountColumn({
                title: '金额',
                dataIndex: 'personAmt',
                onCell: onFieldCell('isPersonAmt'),
                ellipsis: true
            }, { decimalPlaces })
        ]
    },
    amountColumn({
        title: '合计',
        dataIndex: 'totalAmt',
        ellipsis: true
    }, { decimalPlaces }),
    amountColumn({
        title: '上限',
        dataIndex: 'limitUpperAmt',
        onCell: onFieldCell('isLimitUpperAmt'),
        ellipsis: true
    }, { decimalPlaces }),
    amountColumn({
        title: '下限',
        dataIndex: 'limitDownAmt',
        onCell: onFieldCell('isLimitDownAmt'),
        ellipsis: true
    }, { decimalPlaces }),

    {
        title: '小数位',
        dataIndex: 'roundingType',
        width: 120,
        render: text => (
            <span >
                {text
                    ? decimalTypeEnum.getShowName(text)
                    : <EmptyPlaceHolder />}</span>
        ),
        ellipsis: true
    },
    {
        title: '备注',
        dataIndex: 'remark',
        width: 180,
        render(text) {
            return (
                <div
                    style={{
                        minWidth: 100,
                        maxWidth: 350,
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        wordBreak: 'break-all'
                    }}
                >
                    <EmptyPlaceHolder value={text} />
                </div>
            );
        },
        ellipsis: true
    }
];

const getGroupKey = item => item?.housePlace;

const wrapDataSource = dataList => {
    const allData = [].concat(dataList);
    const dataGroup = groupBy(allData, 'housePlace');

    return allData.map((item, index, arr) => {
        const preItem = index === 0 ? null : arr[index - 1];
        const totalAmt = item.status != null ? numberFormat((item.personAmt || 0) + (item.companyAmt || 0), 2, '') : '';

        return {
            ...item,
            totalAmt,
            v_rowSpan: getGroupKey(preItem) !== getGroupKey(item) ? dataGroup[getGroupKey(item)].length : 0
        };
    });
};

const TableWrapper = ({
    columns,
    dataSource,
    showCompareEffect,
    comparePosition,
    hoverRow,
    selectedRow,
    setCurrentHoverRow,
    setCurrentSelectedRow
}) => {
    const tableProps = {
        onRow: record => ({
            className: classnames({
                'row-hover': hoverRow && getGroupKey(hoverRow.row) === getGroupKey(record),
                'row-cell-hover': hoverRow && hoverRow.row.id === record.id,
                'row-selected': selectedRow && selectedRow.row.id === record.id
            }),
            onClick: () => {
                setCurrentSelectedRow({ position: comparePosition, row: record });
            },
            onMouseEnter: () => {
                setCurrentHoverRow({ position: comparePosition, row: record });
            },
            onMouseLeave: () => {
                setCurrentHoverRow(null);
            },
            'data-row-theme': showCompareEffect
                ? (MODIFY_STATUS[record?.status] || MODIFY_STATUS['0'])?.rowTheme || ''
                : ''
        })
    };

    return (
        <div>
            <Table
                size="small"
                tableLayout="fixed"
                columns={columns}
                rowKey="id"
                dataSource={dataSource}
                pagination={false}
                scroll={{ x: 'max-content' }}
                bordered
                {...tableProps}
            />
        </div>
    );
};

const CompareItem = ({
    dataSource,
    showCompareEffect = false,
    comparePosition,
    hoverRow,
    selectedRow,
    setCurrentHoverRow,
    setCurrentSelectedRow
}) => {
    const { contextState: { scale = 2 } } = useContext(BaseSettingContext);
    return <div className="compare-item">
        <TableWrapper
            columns={tableColumn(showCompareEffect, scale)}
            dataSource={wrapDataSource(dataSource)}
            showCompareEffect={showCompareEffect}
            pagination={false}
            comparePosition={comparePosition}
            hoverRow={hoverRow}
            selectedRow={selectedRow}
            setCurrentHoverRow={setCurrentHoverRow}
            setCurrentSelectedRow={setCurrentSelectedRow}
        />
    </div>
};

export default CompareItem;
